import React, { useState } from 'react';
import { DiaryTemplate, TEMPLATE_CATEGORIES } from '../types/templates';
import { useDiaryStore } from '../store/diaryStore';
import { 
  BookOpen, 
  Heart, 
  MapPin, 
  Briefcase, 
  Smile, 
  Target, 
  Moon, 
  Activity, 
  Feather, 
  Users,
  Star,
  Search,
  Filter,
  X
} from 'lucide-react';

interface TemplateSelectorProps {
  onSelect: (template: DiaryTemplate | null) => void;
  onClose: () => void;
  selectedTemplate?: DiaryTemplate | null;
}

const iconMap: { [key: string]: React.ComponentType<any> } = {
  BookOpen,
  Heart,
  MapPin,
  Briefcase,
  Smile,
  Target,
  Moon,
  Activity,
  Feather,
  Users
};

const TemplateSelector: React.FC<TemplateSelectorProps> = ({
  onSelect,
  onClose,
  selectedTemplate
}) => {
  const { 
    getAllTemplates, 
    getTemplatesByCategory, 
    getFavoriteTemplates,
    getMostUsedTemplates,
    toggleTemplateFavorite 
  } = useDiaryStore();
  
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [showFavoritesOnly, setShowFavoritesOnly] = useState(false);
  
  const allTemplates = getAllTemplates();
  const favoriteTemplates = getFavoriteTemplates();
  const mostUsedTemplates = getMostUsedTemplates(3);
  
  const getFilteredTemplates = () => {
    let templates = allTemplates;
    
    // Filter by category
    if (selectedCategory !== 'all') {
      templates = getTemplatesByCategory(selectedCategory);
    }
    
    // Filter by favorites
    if (showFavoritesOnly) {
      templates = templates.filter(t => t.isFavorite);
    }
    
    // Filter by search query
    if (searchQuery) {
      templates = templates.filter(t => 
        t.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        t.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        t.defaultTags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()))
      );
    }
    
    return templates;
  };
  
  const filteredTemplates = getFilteredTemplates();
  
  const handleTemplateSelect = (template: DiaryTemplate) => {
    onSelect(template);
    onClose();
  };
  
  const handleNoTemplate = () => {
    onSelect(null);
    onClose();
  };
  
  const renderTemplateCard = (template: DiaryTemplate) => {
    const IconComponent = iconMap[template.icon] || BookOpen;
    const isSelected = selectedTemplate?.id === template.id;
    
    return (
      <div
        key={template.id}
        className={`relative p-4 rounded-lg border-2 cursor-pointer transition-all duration-200 hover:shadow-md ${
          isSelected 
            ? 'border-blue-500 bg-blue-50' 
            : 'border-gray-200 hover:border-gray-300'
        }`}
        onClick={() => handleTemplateSelect(template)}
      >
        <button
          className={`absolute top-2 right-2 p-1 rounded-full transition-colors ${
            template.isFavorite 
              ? 'text-yellow-500 hover:text-yellow-600' 
              : 'text-gray-400 hover:text-yellow-500'
          }`}
          onClick={(e) => {
            e.stopPropagation();
            toggleTemplateFavorite(template.id);
          }}
        >
          <Star className={`w-4 h-4 ${template.isFavorite ? 'fill-current' : ''}`} />
        </button>
        
        <div className="flex items-start space-x-3">
          <div 
            className="p-2 rounded-lg flex-shrink-0"
            style={{ backgroundColor: `${template.color}20`, color: template.color }}
          >
            <IconComponent className="w-5 h-5" />
          </div>
          
          <div className="flex-1 min-w-0">
            <h3 className="font-semibold text-gray-900 mb-1">{template.name}</h3>
            <p className="text-sm text-gray-600 mb-2">{template.description}</p>
            
            <div className="flex flex-wrap gap-1 mb-2">
              {(template.defaultTags || []).slice(0, 3).map((tag) => (
                <span
                  key={tag}
                  className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded-full"
                >
                  {tag}
                </span>
              ))}
            </div>
            
            <div className="flex items-center justify-between text-xs text-gray-500">
              <span className="capitalize">{template.category}</span>
              <span>{template.sections.length} sections</span>
              {template.usageCount > 0 && (
                <span>Used {template.usageCount} times</span>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };
  
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-hidden">
        {/* Header */}
        <div className="p-6 border-b border-gray-200">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-2xl font-bold text-gray-900">Choose a Template</h2>
            <button
              onClick={onClose}
              className="p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
          
          {/* Search and Filters */}
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <input
                type="text"
                placeholder="Search templates..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
            
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="all">All Categories</option>
              {Object.entries(TEMPLATE_CATEGORIES).map(([key, label]) => (
                <option key={key} value={key}>{String(label)}</option>
              ))}
            </select>
            
            <button
              onClick={() => setShowFavoritesOnly(!showFavoritesOnly)}
              className={`px-4 py-2 rounded-lg border transition-colors flex items-center space-x-2 ${
                showFavoritesOnly
                  ? 'bg-yellow-50 border-yellow-300 text-yellow-700'
                  : 'border-gray-300 text-gray-700 hover:bg-gray-50'
              }`}
            >
              <Star className={`w-4 h-4 ${showFavoritesOnly ? 'fill-current' : ''}`} />
              <span>Favorites</span>
            </button>
          </div>
        </div>
        
        {/* Content */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-200px)]">
          {/* Quick Actions */}
          <div className="mb-6">
            <button
              onClick={handleNoTemplate}
              className="w-full p-4 border-2 border-dashed border-gray-300 rounded-lg text-gray-600 hover:border-gray-400 hover:bg-gray-50 transition-colors"
            >
              <div className="flex items-center justify-center space-x-2">
                <BookOpen className="w-5 h-5" />
                <span>Start with blank entry (no template)</span>
              </div>
            </button>
          </div>
          
          {/* Most Used Templates */}
          {mostUsedTemplates.length > 0 && !searchQuery && selectedCategory === 'all' && !showFavoritesOnly && (
            <div className="mb-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-3">Most Used</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {mostUsedTemplates.map(renderTemplateCard)}
              </div>
            </div>
          )}
          
          {/* Favorite Templates */}
          {favoriteTemplates.length > 0 && !searchQuery && selectedCategory === 'all' && !showFavoritesOnly && (
            <div className="mb-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-3">Favorites</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {favoriteTemplates.slice(0, 6).map(renderTemplateCard)}
              </div>
            </div>
          )}
          
          {/* All Templates */}
          <div>
            <h3 className="text-lg font-semibold text-gray-900 mb-3">
              {searchQuery || selectedCategory !== 'all' || showFavoritesOnly 
                ? `Templates (${filteredTemplates.length})` 
                : 'All Templates'
              }
            </h3>
            
            {filteredTemplates.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <Filter className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                <p>No templates found matching your criteria.</p>
                <p className="text-sm">Try adjusting your search or filters.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {filteredTemplates.map(renderTemplateCard)}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default TemplateSelector;